﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jvm.rtda.heap.clazz.clazz
{
    class ClassNameHelper
    {
        public static Dictionary<string, string> map = new Dictionary<string, string>()
        {
            {"void", "V" },
            {"boolean", "Z" },
            {"byte" ,"B" },
            {"short", "S" },
            {"int" ,"I" },
            {"long" ,"L" },
            {"char", "C" },
            {"float", "F" },
            {"double" ,"D" }
        };

        // 外面加一层数组标记
        public static string GetArrayClassName(string classname)
        {
            return "[" + ToDescriptor(classname);
        }

        // 剥离掉数组标记
        public static string GetInnerClassName(string classname)
        {
            if (classname[0] == '[')
            {
                return ToClassName(classname.Substring(1));
            }
            Console.WriteLine("Not Array");
            Environment.Exit(0);
            return string.Empty;
        }

        // [XXX => [XXX
        // int  => I
        // XXX  => LXXX;
        static string ToDescriptor(string classname)
        {
            if (classname[0] == '[')
            {
                return classname;
            }
            if (map.ContainsKey(classname))
            {
                return map[classname];
            }
            return "L" + classname + ";";
        }

        // [XXX  => [XXX
        // LXXX; => XXX
        // I     => int
        static string ToClassName(string classname)
        {
            if (classname[0] == '[')
            {
                return classname;
            }
            if (classname[0] == 'L')
            {
                return classname.Substring(1, classname.Length - 2);
            }
            foreach (KeyValuePair<string, string> entry in map)
            {
                if (entry.Value.Equals(classname))
                {
                    return entry.Key;
                }
            }
            Console.WriteLine("Invalid Descriptor");
            Environment.Exit(0);
            return string.Empty;
        }
    }
}
